package net.mimai.vultrue.bus.excel.reader.parser;


import net.mimai.vultrue.bus.excel.reader.handler.IExcelParseHandler;
import net.mimai.vultrue.bus.excel.reader.handler.impl.Excel2003ParseHandler;
import net.mimai.vultrue.bus.excel.reader.handler.impl.Excel2007ParseHandler;
import org.apache.poi.poifs.filesystem.FileMagic;

import java.io.InputStream;

public class ExcelSaxParser<T> extends AbstractExcelParser<T> {

    @Override
    public IExcelParseHandler<T> createHandler(InputStream excelInputStream) {
//        try {
//            byte[] header8 = IOUtils.peekFirst8Bytes(excelInputStream);
//            if (NPOIFSFileSystem.hasPOIFSHeader(header8)) {
//                return new Excel2003ParseHandler<>();
//            } else if (DocumentFactoryHelper.hasOOXMLHeader(excelInputStream)) {
//                return new Excel2007ParseHandler<>();
//            } else {
//                throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
//            }
//        } catch (Exception e) {
//            logger.error("getParserInstance Error!", e);
//            throw new RuntimeException(e);
//        }
       // == FileMagic.OOXML
        try {

            FileMagic fileMagic = FileMagic.valueOf(excelInputStream);
            switch (fileMagic){
                case OOXML:
                    return new Excel2007ParseHandler<>();
                case OLE2:
                    return new Excel2003ParseHandler<>();
                default:
                    throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
            }
        } catch (Exception e) {
            logger.error("getParserInstance Error!", e);
            throw new RuntimeException(e);
        }
    }

}
